<?php
namespace app\api\server;


use app\common\server\storage\Driver as StorageDriver;
use app\common\server\UrlServer;
use think\Db;
use think\Exception;
use app\common\server\ConfigServer;
use think\facade\Hook;
use think\facade\Env;
use think\facade\Cache;

class UserServer
{
    /**
     * Desc: 通过小程序创建用户信息
     * @param $response
     * @param $client
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws Exception
     */
    public static function createUser($response, $client)
    {
        $user_info = [];
        try {
            $openid = $response['openid'];
            $unionid = $response['unionid'] ?? '';
            $avatar_url = $response['avatar'] ?? '';
            $nickname = $response['nickname'] ?? '';

            Db::startTrans();

            // 获取存储引擎
            $config = [
                'default' => ConfigServer::get('storage', 'default', 'local'),
                'engine'  => ConfigServer::get('storage_engine')
            ];

            $time   = time(); //创建时间
            $avatar = '';     //头像路径

            if (empty($avatar_url)) {
                $avatar = ConfigServer::get('website', 'user_image');
            } else {
                if ($config['default'] == 'local') {
                    $file_name = md5($openid . $time) . '.jpeg';
                    $avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
                } else {
                    $avatar = 'uploads/user/avatar/' . md5($openid . $time) . '.jpeg';
                    $StorageDriver = new StorageDriver($config);
                    if (!$StorageDriver->fetch($avatar_url, $avatar)) {
                        throw new Exception( '头像保存失败:'. $StorageDriver->getError());
                    }
                }
            }
            $data = [
                'nickname'          => $nickname,
                'sn'                => create_user_sn(),
                'avatar'            => $avatar,
                'create_time'       => $time,
                // 微信新用户
                'is_new_user'       => 1,
            ];
            if (empty($nickname)) {
                $data['nickname'] = '用户'.$data['sn'];
            }
            $APPID =config('wechat.app_id');
            $APPSECRET=config('wechat.secret');
            // $data['distribution_mnp_qr_code']=self::getXcxCode($APPID,$APPSECRET,$data['distribution_code']);

            $user_id = Db::name('user')
                ->insertGetId($data);

            $data = [
                'user_id' => $user_id,
                'openid' => $openid,
                'create_time' => $time,
                'unionid' => $unionid,
                'client' => $client,
            ];
            Db::name('user_auth')
                ->insert($data);

            // //生成会员分销扩展表
            // DistributionLogic::createUserDistribution($user_id);
            // //绑定推荐人
            // if($distribution_code){
            //     DistributionLogic::code($distribution_code,$user_id);
            // }
            //注册赠送优惠
            //LoginLogic::registerAward($user_id);
            Db::commit();
            $user_info = Db::name('user')
                ->field(['id', 'nickname', 'avatar', 'disable','is_new_user'])
                ->where(['id' => $user_id])
                ->find();
            if (empty($user_info['avatar'])) {
                $user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
            } else {
                $user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']);
            }
            // $user_info['distribution_mnp_qr_code'] = UrlServer::getFileUrl($user_info['distribution_mnp_qr_code']);
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        return $user_info;
    }

    //拿到token获取二维码
    public static function getXcxCode($APPID,$APPSECRET,$code){
        $access_token=Cache::get('access_token');
        if ($access_token) {
            $accessToken= $access_token;
        }else{
            $accessToken = self::DoctorAccessToken($APPID,$APPSECRET);
        }
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $data=[
          //'access_token'=>$accessToken,
          'scene'=>$code,   
          'page'=>'pages/home/vendor',    
          'width'=>430,
          'auto_color'=>false,
          'check_path'=>false,
          'env_version'=>"release",
        ];
        $data=json_encode($data);
        //拿到二维码
        $result =self::curl_post_https($url,$data);
        //把二维码存到服务器端
        return self::UploadImageQrCode($result);
    }

    public static function curl_post_https($url, $post_data)
    {
        $headers = array();
        $headers[] = "Content-Type:application/json";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//设置请求头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');//使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。(这个加不加没啥影响)
        $result = curl_exec($curl);
        return $result;
    }

    // 图片上传
    public static function UploadImageQrCode($img){
        $saveimgfile_1 = Env::get('root_path').'public/wxcode/';
        $fileimgname = time()."-".rand(1000,9999).".png";
        $filecachs = $saveimgfile_1.$fileimgname;
        $fanhuistr = file_put_contents($filecachs,$img);
        return '/wxcode/'.$fileimgname;
    }

    //获取token缓存起来
    public static function DoctorAccessToken($APPID,$APPSECRET){
        //创建请求数据
        $url_token="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APPID}&secret={$APPSECRET}";
        $data_result = curl_request($url_token);
        $data_two = json_decode($data_result,TRUE);
        $token = $data_two['access_token'];
        Cache::set('access_token',$token,7150);
        return $token;
    }

    /**
     * 更新用户信息
     * @param $response
     * @param $client
     * @param $user_id
     * @return array|\PDOStatement|string|\think\Model|null
     */
    public static function updateUser($response, $client, $user_id)
    {
        $time = time();
        try {

            $openid = $response['openid'];
            $unionid = $response['unionid'] ?? '';
            $avatar_url = $response['avatar'] ?? '';
            $nickname = $response['nickname'] ?? '';
            Db::startTrans();

            //用户已存在，但是无该端的授权信息，保存数据
            $user_auth_id = Db::name('user_auth')
                ->where(['user_id' => $user_id, 'openid' => $openid])
                ->value('id');

            if (empty($user_auth_id)) {
                $data = [
                    'create_time' => $time,
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'user_id' => $user_id,
                    'client' => $client,
                ];
                Db::name('user_auth')
                    ->insert($data);
            }

            $user_info = Db::name('user u')
                ->field(['u.nickname', 'u.avatar', 'u.id', 'au.unionid'])
                ->join('user_auth au', 'u.id=au.user_id')
                ->where(['au.openid' => $openid])
                ->find();

            //无头像需要更新头像
            if (empty($user_info['avatar'])) {
                // 获取存储引擎
                $config = [
                    'default' => ConfigServer::get('storage', 'default', 'local'),
                    'engine'  => ConfigServer::get('storage_engine')
                ];

                $avatar = '';     //头像路径
                if ($config['default'] == 'local') {
                    $file_name = md5($openid . $time) . '.jpeg';
                    $avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
                } else {
                    $avatar = 'uploads/user/avatar/' . md5($openid . $time) . '.jpeg';
                    $StorageDriver = new StorageDriver($config);
                    if (!$StorageDriver->fetch($avatar_url, $avatar)) {
                        throw new Exception( '头像保存失败:'. $StorageDriver->getError());
                    }
                }

                $data['avatar'] = $avatar;
                $data['update_time'] = $time;
                $data['nickname'] = $nickname;
                Db::name('user')
                    ->where(['id' => $user_info['id']])
                    ->update($data);
            }

            //之前无unionid需要更新
            if (empty($user_info['unionid']) && isset($unionid)) {
                $data = [];
                $data['unionid'] = $unionid;
                $data['update_time'] = $time;
                Db::name('user_auth')
                    ->where(['user_id' => $user_info['id']])
                    ->update($data);
            }

            $user_info = Db::name('user')
                ->where(['id' => $user_info['id']])
                ->field(['id', 'nickname', 'avatar', 'disable', 'is_new_user'])
                ->find();

            if (empty($user_info['avatar'])) {
                $user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
            } else {
                $user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']);
            }
            // $user_info['distribution_mnp_qr_code'] = UrlServer::getFileUrl($user_info['distribution_mnp_qr_code']);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        return $user_info;
    }
}